/*
** Arkanoid driver for testing AY8910s
** This is pretty much identical to the M1 driver
*/

#include "smse2kincludes.h"
#include "CPUFactory.h"
#include "SoundDeviceFactory.h"
#include "ArkanoidDriver.h"

UINT8 ark_patch[0x11] = {
	0x31, 0xc0, 0xc0, 0x3e, 0x0a, 0xcd, 0xae, 0x67,
	0xcd, 0x92, 0x67, 0xcd, 0xbe, 0x15, 0xc3, 0x09,
	0x00,

};

// ROMs: a75-01-1.rom loaded at 0x0000
//		 a75-11.rom   loaded at 0x8000

int CArkanoidDriver::Load(const char* fn) {
	// Load files
	FILE_HANDLE rom1 = filesystem.OpenFile("a75-01-1.rom",FSYS_PERMISSION_READ);
	FILE_HANDLE rom2 = filesystem.OpenFile("a75-11.rom",FSYS_PERMISSION_READ);
	
	memset(this->memspace,0,0xffff);
	filesystem.Read(rom1,memspace,0x8000);
	filesystem.Read(rom2,memspace + 0x8000,0x8000);
	filesystem.CloseFile(rom1);
	filesystem.CloseFile(rom2);

	// patch
	memcpy(memspace + 1, ark_patch, 0x10);


	return 0;
}

int CArkanoidDriver::Init(CHardware* hardware) {

	ay = SoundDeviceFactory("AY8910");
	z80 = CPUFactory("Z80");
	z80->Init(6000000/13);
	z80->AssignMMU(0, this);


	ay->Init(hardware->mixer, 1500000); 

	hardware->AddCpu(z80); // assign the z80 to the scheduler
	

	// clear RAM
	memset(memspace + 0xc000, 0, 0x800);
	memset(memspace + 0xe000, 0, 0x1000);

	return 0;
}

void CArkanoidDriver::FreeUnusedResources() {

}

void CArkanoidDriver::Close() {

}

void CArkanoidDriver::Write8(UINT64 offset, UINT8 data) {
	memspace[offset & 0xffff] = data;
	//Msg("Write8: %04X\n",offset);

	if ((offset == 0xd000) || (offset == 0xd001)) ay->Write(offset & 1, data);
}

UINT8 CArkanoidDriver::Read8(UINT64 offset) {
	if (offset == 0xd001) return ay->Read(0);
	return memspace[offset & 0xffff];
}

// Driver stuff.
DRIVER_DOES_NOT_SUPPORT_FILETYPES(CArkanoidDriver);
DRIVER_FACTORY("arkanoid","Arkanoid Test",1,CArkanoidDriver);